﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.Configuration;

namespace AppSeguro.Models
{
    public class Usuario
    {
        public int Id { get; set; }
        public string Nome { get; set; }
        public string Login { get; set; }
        public string Senha { get; set; }
        public string Email { get; set; }

        public Usuario()
        {
        }
        public Usuario(int pId
                     , string pNome
                     , string pLogin
                     , string pSenha
                     , string pEmail
                  )
        {
            Id = pId;
            Nome = pNome;
            Login = pLogin;
            Senha = pSenha;
            Email = pEmail;
        }

        public void Carregar(int id)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("select ");
            sql.Append("Id");
            sql.Append(",Nome");
            sql.Append(",Login");
            sql.Append(",Senha");
            sql.Append(",Email");
            sql.Append(" from  Usuario");
            sql.Append(" WHERE Id = @Id");


            var connString = WebConfigurationManager.ConnectionStrings["TCC-SEGURO"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                var command = new SqlCommand(sql.ToString(), conn);
                command.Parameters.Add("@Id", SqlDbType.Int).Value = id;
                command.Connection.Open();
                List<Usuario> u = new List<Usuario>();

                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    this.Id = Convert.ToInt32(reader.GetValue(0).ToString());
                    this.Nome = reader.GetValue(1).ToString();
                    this.Login = reader.GetValue(2).ToString();
                    this.Senha = reader.GetValue(3).ToString();
                    this.Email = reader.GetValue(4).ToString();
                }
            }
        }

        public bool CarregarLogin(string Login, string Senha)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("id");
            sql.Append(",nome");
            sql.Append(",login");
            sql.Append(",senha");
            sql.Append(",email");
            sql.Append(" from  usuario");
            sql.Append(" WHERE login = @Login");
            sql.Append(" AND senha = @Senha");

            var connString = WebConfigurationManager.ConnectionStrings["TCC-SEGURO"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                var command = new SqlCommand(sql.ToString(), conn);
                /* O campo abaixo é utilizado para recuperar a senha criptografada e inserir 
                 * manualmente no banco, tendo em vista que não foi criada uma página de cadastro 
                 * de usuários do sistema */
                //string senhaCriptografada = RepositorioCriptografia.Criptografar(Senha); 
                command.Parameters.Add("@Login", SqlDbType.NVarChar).Value = Login;
                command.Parameters.Add("@Senha", SqlDbType.NVarChar).Value = RepositorioCriptografia.Criptografar(Senha);
                command.Connection.Open();
                List<Usuario> u = new List<Usuario>();

                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    this.Id = Convert.ToInt32(reader.GetValue(0).ToString());
                    this.Nome = reader.GetValue(1).ToString();
                    this.Login = reader.GetValue(2).ToString();
                    this.Senha = reader.GetValue(3).ToString();
                    this.Email = reader.GetValue(4).ToString();
                    return true;
                }
            }
            return false;
        }


        public static Usuario UsuarioLogado(HttpSessionStateBase session)
        {
            if (session.Count == 0)
            {
                return null;
            }
            // Descriptografa cada atributo da session
            int id = Convert.ToInt32(RepositorioCriptografia.
                Descriptografar(session["Id"].ToString()));
            string nome = RepositorioCriptografia.
                Descriptografar(session["Nome"].ToString());
            string email = RepositorioCriptografia.
                Descriptografar(session["Email"].ToString());

            Usuario us = new Usuario().CarregarSessao(id, nome, email);
            if (us == null)
            {
                return null;
            }
            return us;
        }

        private Usuario CarregarSessao(int id, string nome, string email)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("id");
            sql.Append(",nome");
            sql.Append(",login");
            sql.Append(",senha");
            sql.Append(",email");
            sql.Append(" from  usuario");
            sql.Append(" WHERE id = @Id");
            sql.Append(" AND nome = @Nome");
            sql.Append(" AND email = @Email");

            var connString = WebConfigurationManager.ConnectionStrings["TCC-SEGURO"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                var command = new SqlCommand(sql.ToString(), conn);
                command.Parameters.Add("@Id", SqlDbType.Int).Value = id;
                command.Parameters.Add("@Nome", SqlDbType.NVarChar).Value = nome;
                command.Parameters.Add("@Email", SqlDbType.NVarChar).Value = email;
                command.Connection.Open();

                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    this.Id = Convert.ToInt32(reader.GetValue(0).ToString());
                    this.Nome = reader.GetValue(1).ToString();
                    this.Login = reader.GetValue(2).ToString();
                    this.Senha = reader.GetValue(3).ToString();
                    this.Email = reader.GetValue(4).ToString();
                    return this;
                }
            }
            return null;
        }
    }
}